<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationBarTitleText: '创建比赛',
  },
}
</route>
<template>
  <view
    class="overflow-hidden flex flex-col h-full"
    :style="{ marginTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="mt-4 mb-2">
      <wd-steps :active="currentStep" align-center>
        <wd-step title="比赛信息" />
        <wd-step title="设置组别" />
        <wd-step title="宣传信息" />
      </wd-steps>
    </view>
    <view class="flex-1 bg-gray-1 overflow-hidden">
      <view v-if="currentStep == 0" class="tournament-step-panel">
        <view class="tournament-step-panel__content">
          <wd-form ref="tournamentForm" :model="tournamentInfo" errorType="message">
            <wd-cell-group border title="比赛名称">
              <wd-textarea
                placeholder="请输入比赛标题至少5个字，不超过24个字"
                show-word-limit
                prop="name"
                :fixed="false"
                :maxlength="100"
                v-model="tournamentInfo.name"
                :rules="[{ required: true, message: '请填写赛事名称' }]"
              ></wd-textarea>
            </wd-cell-group>
            <wd-cell-group border class="my-2" title="比赛时间">
              <wd-datetime-picker
                label="开始"
                placeholder="请选择开始时间"
                prop="fromDate"
                v-model="tournamentInfo.fromDate"
                :min-date="Date.now()"
                :rules="[
                  { required: true, validator: validateMatchStartData, message: '请选择开始时间' },
                ]"
              />
              <wd-datetime-picker
                label="结束"
                placeholder="请选择结束时间"
                prop="endDate"
                v-model="tournamentInfo.endDate"
                :min-date="Date.now()"
                :rules="[
                  { required: true, message: '请选择结束时间', validator: validateMatchEndData },
                ]"
              />
            </wd-cell-group>
            <wd-cell-group border class="my-2" title="报名时间">
              <wd-datetime-picker
                label="开始"
                placeholder="请选择开始时间"
                prop="registrationFromDate"
                v-model="tournamentInfo.registrationFromDate"
                :min-date="Date.now()"
                :rules="[
                  {
                    required: true,
                    message: '请选择开始时间',
                    validator: validateRegisterStartData,
                  },
                ]"
              />
              <wd-datetime-picker
                label="结束"
                placeholder="请选择结束时间"
                prop="registrationEndDate"
                v-model="tournamentInfo.registrationEndDate"
                :min-date="Date.now()"
                :rules="[
                  {
                    required: true,
                    message: '请选择结束时间',
                    validator: validateRegisterEndData,
                  },
                ]"
              />
            </wd-cell-group>
            <wd-cell-group border class="my-2" title="比赛地址">
              <wd-textarea
                placeholder="请输入比赛地址"
                show-word-limit
                :fixed="false"
                :maxlength="200"
                v-model="tournamentInfo.address"
                prop="address"
                :rules="[{ required: true, message: '请填写比赛地址' }]"
              ></wd-textarea>
            </wd-cell-group>
            <wd-cell-group border class="my-2" title="联系人">
              <wd-cell
                v-for="user in tournamentInfo.concatUserList"
                :key="user.id"
                :value="user.phone"
              >
                <template #title>
                  <wd-button
                    type="default"
                    icon="minus-circle"
                    @click="() => handleUseRemove(user)"
                  >
                    {{ user.name }}
                  </wd-button>
                </template>
              </wd-cell>
              <wd-cell>
                <template #title>
                  <wd-button type="default" icon="add-circle" @click="handleUserAdd()">
                    添加联系人
                  </wd-button>
                </template>
              </wd-cell>
            </wd-cell-group>
          </wd-form>
        </view>
        <view class="tournament-step-panel__footer">
          <wd-button type="primary" :round="false" block size="large" @click="goStep(1)">
            下一步
          </wd-button>
        </view>
      </view>
      <view v-if="currentStep == 1" class="tournament-step-panel">
        <view class="tournament-step-panel__content">
          <wd-card v-for="category in tournamentInfo.categories" :key="category._key">
            <template #title>
              <view>
                <view>{{ category.name }} | {{ category.alias }}</view>
                <view>年龄: {{ category.minAge }}-{{ category.maxAge }}</view>
              </view>
            </template>
            <!-- <wd-checkbox-group shape="button" v-model="category._eventList" disabled="true">
              <wd-checkbox
                v-for="eventItem in category._eventList"
                :modelValue="eventItem"
                :key="eventItem"
              >
                {{ eventTypeEnum[eventItem] }}
              </wd-checkbox>
            </wd-checkbox-group> -->
            <wd-tag
              v-for="eventItem in category._eventList"
              type="primary"
              round
              :key="eventItem.value"
            >
              {{ eventTypeEnum[eventItem] }}
            </wd-tag>
            <template #footer>
              <wd-button
                size="small"
                plain
                type="error"
                icon="delete"
                class="mx-2"
                @click="handleCategoryRemove(category)"
              >
                删除
              </wd-button>
              <wd-button
                size="small"
                plain
                type="info"
                icon="edit"
                @click="
                  (e) => {
                    handleCategoryAdd(category)
                  }
                "
              >
                编辑
              </wd-button>
            </template>
          </wd-card>
          <view>
            <wd-button icon="add" block @click="handleCategoryAdd">添加组别</wd-button>
          </view>
        </view>
        <view class="tournament-step-panel__footer">
          <wd-button type="info" :round="false" block size="large" @click="goStep(0)">
            上一步
          </wd-button>
          <wd-button type="primary" :round="false" block size="large" @click="goStep(2)">
            下一步
          </wd-button>
        </view>
      </view>
      <view v-if="currentStep == 2" class="tournament-step-panel">
        <view class="tournament-step-panel__content">
          <wd-card>
            <view class="flex justify-center">
              <wd-upload
                reupload
                class="justify-center"
                action="https://mockapi.eolink.com/zhTuw2P8c29bc981a741931bdd86eb04dc1e8fd64865cb5/upload"
              ></wd-upload>
            </view>
            <view class="text-center">上传宣传图</view>
          </wd-card>
          <wd-card>
            <view class="flex justify-center">
              <wd-upload
                reupload
                action="https://mockapi.eolink.com/zhTuw2P8c29bc981a741931bdd86eb04dc1e8fd64865cb5/upload"
              ></wd-upload>
            </view>
            <view class="text-center">上传详情图</view>
          </wd-card>
        </view>
        <view class="tournament-step-panel__footer">
          <wd-button type="info" :round="false" block size="large" @click="goStep(1)">
            上一步
          </wd-button>
          <wd-button type="primary" :round="false" block size="large" @click="createTournament">
            发布比赛
          </wd-button>
        </view>
      </view>
    </view>
    <drawer ref="userDrawer" title="联系人">
      <wd-form
        ref="userForm"
        class="flex-1"
        title="联系人"
        :model="userFormModel"
        errorType="message"
      >
        <wd-input
          name="input"
          prop="name"
          label="名称"
          placeholder="请输入"
          required
          v-model="userFormModel.name"
          :rules="[{ required: true, message: '请填写名称' }]"
        ></wd-input>
        <wd-input
          name="input"
          prop="phone"
          label="电话号码"
          placeholder="请输入"
          type="digit"
          required
          v-model="userFormModel.phone"
          :rules="[{ required: true, message: '请填写电话号码' }]"
        ></wd-input>
      </wd-form>
      <template v-slot:footer>
        <wd-button
          type="info"
          size="large"
          :round="false"
          class="flex-1 mr-2"
          @click="handleUserDrawerCancel"
        >
          取消
        </wd-button>
        <wd-button
          type="primary"
          size="large"
          :round="false"
          class="flex-1"
          @click="handleUserDrawerConfirm"
        >
          确定
        </wd-button>
      </template>
    </drawer>
    <drawer title="组别" ref="categoryDrawer">
      <wd-form ref="categoryForm" class="flex-1" title="组别" :model="categoryFormModel">
        <wd-input
          name="input"
          prop="name"
          label="组别名称"
          placeholder="请输入"
          required
          v-model="categoryFormModel.name"
          :rules="[{ required: true, message: '请填写组别名称' }]"
        ></wd-input>
        <wd-input
          name="input"
          prop="alias"
          label="组别代号"
          placeholder="请输入"
          required
          v-model="categoryFormModel.alias"
          :rules="[{ required: true, message: '请填写组别代号' }]"
        ></wd-input>
        <wd-cell-group border>
          <wd-cell title="参赛年龄" size="large" vertical>
            <wd-slider
              prop="alias"
              label="年龄"
              placeholder="请输入"
              required
              v-model="categoryAgeRange"
            ></wd-slider>
          </wd-cell>
          <wd-cell title="参赛项目" size="large" vertical>
            <block v-if="eventTypes.length">
              <wd-checkbox-group
                props="_eventList"
                v-model="categoryFormModel._eventList"
                shape="button"
                :rules="[{ required: true, message: '请选择参赛项目' }]"
              >
                <wd-checkbox
                  v-for="eventItem in eventTypes"
                  :key="eventItem.value"
                  :model-value="eventItem.value"
                >
                  {{ eventItem.name }}
                </wd-checkbox>
              </wd-checkbox-group>
            </block>
          </wd-cell>
        </wd-cell-group>
      </wd-form>
      <template v-slot:footer>
        <wd-button
          type="info"
          size="large"
          :round="false"
          class="flex-1 mr-2"
          @click="handleCategoryDrawerCancel"
        >
          取消
        </wd-button>
        <wd-button
          type="primary"
          size="large"
          :round="false"
          class="flex-1"
          @click="handleCategoryDrawerConfirm"
        >
          确定
        </wd-button>
      </template>
    </drawer>
  </view>
</template>

<script lang="ts" setup>
import { getTournamentInfo, getBizConstant, saveTournament } from '@/service/tournament'
import { useMessage, useToast } from 'wot-design-uni'
import drawer from '@/components/drawer/drawer.vue'
import { EventTypeText } from '@/common/enum'
import dayjs from 'dayjs'

/** options */
defineOptions({
  name: 'GameDetail',
})

const { safeAreaInsets } = uni.getSystemInfoSync()
const messageBox = useMessage()

/** data */
const currentStep = ref<number>(0)
const tournamentInfo = ref<Tournament>({
  name: '',
  fromDate: null,
  endDate: null,
  address: '',
  status: 1,
  type: 1,
  adImage: 'https://dummyimage.com/400x200/3c9cff/fff',
  detailImage: 'https://dummyimage.com/400x200/3c9cff/fff',
  concatUserList: [],
  categories: [],
})
const tournamentForm = ref(null)

const userForm = ref(null)
const userFormModel = ref<User>(null)
const userDrawer = ref(null)

const categoryForm = ref(null)
const categoryFormModel = ref<Category>(null)
const categoryAgeRange = ref<number[]>([0, 100])
const categoryDrawer = ref(null)

const eventTypes = ref([])
const eventTypeEnum = {}
const toast = useToast()

/** lifecycle */
onMounted(() => {})

onShow(async () => {
  // const { data: res } = await getBizConstant()
  eventTypes.value = []
  Object.entries(EventTypeText).forEach(([key, value]) => {
    eventTypes.value.push({ value: Number(key), name: value })
    eventTypeEnum[key] = value
  })
})
const createTournament = async () => {
  console.log(tournamentInfo.value)
  const res = await saveTournament(tournamentInfo.value)
  if (res) {
    toast.success('赛事创建成功!')
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
}

function handleUseRemove(user: User) {
  messageBox
    .confirm({
      title: '提示',
      msg: '确定要删除该联系人吗？',
    })
    .then(() => {
      tournamentInfo.value.concatUserList = tournamentInfo.value.concatUserList.filter(
        (item) => item.id !== user.id,
      )
    })
}

function handleUserAdd() {
  userFormModel.value = {
    _key: Date.now(),
    name: '',
    phone: '',
  }

  userDrawer.value.open()
}

function handleCategoryRemove(category: Category) {
  messageBox
    .confirm({
      title: '提示',
      msg: '确定要删除该组别吗？',
    })
    .then(() => {
      tournamentInfo.value.categories = tournamentInfo.value.categories.filter(
        (item) => item._key !== category._key,
      )
    })
}

function handleUserDrawerConfirm() {
  userForm.value.validate().then(({ valid, errors }) => {
    if (!valid) {
      return
    }

    tournamentInfo.value.concatUserList.push(userFormModel.value)
    userDrawer.value.close()
  })
}

function handleUserDrawerCancel() {
  userDrawer.value.close()
}

function handleCategoryAdd(category?: any) {
  if (category._key) {
    categoryFormModel.value = category
  } else {
    categoryFormModel.value = {
      _key: Date.now(),
      _eventList: [],
      name: '',
      alias: '',
      minAge: 0,
      maxAge: 100,
    }
  }
  categoryAgeRange.value = [categoryFormModel.value.minAge, categoryFormModel.value.maxAge]
  categoryDrawer.value.open()
}

function handleCategoryDrawerConfirm() {
  categoryForm.value.validate().then(({ valid, errors }) => {
    if (!valid) {
      return
    }
    if (categoryFormModel.value._eventList.length === 0) {
      toast.error('请选择参赛项目')
      return
    }

    let isUpdate = false
    const newCategory = {
      ...categoryFormModel.value,
      minAge: categoryAgeRange.value[0],
      maxAge: categoryAgeRange.value[1],
      events: categoryFormModel.value._eventList.map((item) => {
        return { type: item }
      }),
    }
    tournamentInfo.value.categories.forEach((item, index) => {
      if (isUpdate) {
        return
      }
      if (item._key === categoryFormModel.value._key) {
        tournamentInfo.value.categories.splice(index, 1, newCategory)
        isUpdate = true
      }
    })
    if (!isUpdate) {
      tournamentInfo.value.categories.push(newCategory)
    }

    categoryDrawer.value.close()
  })
}

function handleCategoryDrawerCancel() {
  categoryDrawer.value.close()
}

function goStep(step: number) {
  if (currentStep.value > step) {
    // 回退，不做校验
    currentStep.value = step
  } else {
    if (step === 1) {
      // 校验
      tournamentForm.value.validate().then(({ valid, errors }) => {
        if (!valid) {
          return
        }
        currentStep.value = step
      })
    } else if (step === 2) {
      if (!tournamentInfo.value?.categories?.length) {
        toast.error('请添加组别')
      } else {
        currentStep.value = step
      }
    } else {
      currentStep.value = step
    }
  }
}

const validateMatchStartData = () => {
  if (!tournamentInfo.value.fromDate) {
    return Promise.reject(Error('比赛开始时间不能为空'))
  } else if (dayjs(tournamentInfo.value.fromDate).isBefore(new Date())) {
    return Promise.reject(Error('比赛开始时间不能在当前时间之前'))
  } else {
    return Promise.resolve()
  }
}
const validateMatchEndData = () => {
  if (!tournamentInfo.value.endDate) {
    return Promise.reject(Error('比赛结束时间不能为空'))
  } else if (dayjs(tournamentInfo.value.endDate).isBefore(tournamentInfo.value.fromDate)) {
    return Promise.reject(Error('比赛结束时间不能在当前时间之前'))
  } else {
    return Promise.resolve()
  }
}
const validateRegisterStartData = () => {
  if (!tournamentInfo.value.registrationFromDate) {
    return Promise.reject(Error('报名开始时间不能为空'))
  } else {
    return Promise.resolve()
  }
}
const validateRegisterEndData = () => {
  if (!tournamentInfo.value.registrationEndDate) {
    return Promise.reject(Error('报名结束时间不能为空'))
  } else if (
    dayjs(tournamentInfo.value.registrationEndDate).isBefore(
      tournamentInfo.value.registrationFromDate,
    )
  ) {
    return Promise.reject(Error('报名结束时间不能在当前时间之前'))
  } else {
    return Promise.resolve()
  }
}

function handleFormReset() {
  console.log('form发生了reset事件')
}
</script>

<style lang="scss">
.tournament-step-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;

  &__content {
    flex: 1;
    padding: 8px;
    overflow-y: auto;
  }

  &__footer {
    display: flex;
    padding: 8px;
    background: white;

    .wd-button {
      flex: 1;
      margin: 0 4px;

      &:first-child {
        margin-left: 0;
      }
    }
  }
}
</style>
